<!--
 * @Author: your name
 * @Date: 2022-03-30 09:25:18
 * @LastEditTime: 2022-03-30 09:39:21
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \geyao\geyao\单体模式220330.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>单体模式</title>
</head>

<body>
  <script>
    // 单体模式 只能实例化一次 每次返回的实例是同一对象
    var Singleton = function (name) {
      this.name = name;
    };
    Singleton.prototype.getName = function () {
      return this.name;
    }
    // 获取实例对象
    var getInstance = (function () {
      var instance = null;
      return function (name) {
        console.log(name,"name")
        //如果实例不存在 重新新加个实例
        if (!instance) {
          instance = new Singleton(name);
        }
        
        return instance;
      }
    })();
    // 测试单体模式的实例
    var a = getInstance("aa");
    var b = getInstance("bb");
    console.log(a,"a") //aa
    console.log(b,"b") //aa
  </script>
</body>

</html>